//============================================================================
// Name        : askme.cpp
// Author      : sjfan
// Version     :
// Copyright   : 1.0
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <stdio.h>
#include <stdlib.h>
#include <linux/rtc.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <time.h>
#include <sys/time.h>
#include <sys/vfs.h>

#include "msgStruct.h"

#define MAXLINE 64
#define Gsize (1024.00*1024.00*1024.00)
Msg_t udpmsg;

char* cmd_system(const char* command) {
	char* result = "";
	FILE *fpRead;
	fpRead = popen(command, "r");
	char buf[1024];
	memset(buf, '\0', sizeof(buf));
	while (fgets(buf, 1024 - 1, fpRead) != NULL) {
		result = buf;
	}
	if (fpRead != NULL)
		pclose(fpRead);
	return result;
}

void pushstatus(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen) {
	int fromcnt = 0;
	int sndcnt = 0;
	char sndbuf[MAXLINE + 1];
	struct statfs fs;
	float freepos = 0;
	for (;;) {
		/* waiting for receive data */
		memset(&udpmsg, 0, sizeof(udpmsg));
		fromcnt = recvfrom(sockfd, &udpmsg, sizeof(udpmsg), 0, pcliaddr,
				&clilen);
		if (fromcnt >= 0) {
			if (!strcmp(udpmsg.opType, "stat")) {
				sprintf(sndbuf, "OKOKOK\n");
				sndcnt = sendto(sockfd, sndbuf, strlen(sndbuf), 0, pcliaddr,
						clilen);
				printf("UDP SND=%d\n", sndcnt);
			}
			if (!strcmp(udpmsg.opType, "free")) {
				if (statfs(udpmsg.arg1, &fs) < 0) {
					sprintf(sndbuf, "%s error statfs\n", udpmsg.arg1);
				} else {
					freepos = (double) fs.f_bfree / fs.f_blocks * 100.0;
					sprintf(sndbuf, "%.2f%[%.2f G]\n", freepos,
							fs.f_blocks * fs.f_bsize / Gsize);
				}
				sndcnt = sendto(sockfd, sndbuf, strlen(sndbuf), 0, pcliaddr,
						clilen);
			}
		}
	}
}

int main() {

	int sockfd;
	struct sockaddr_in servaddr, cliaddr;
	int cpu;

	sockfd = socket(AF_INET, SOCK_DGRAM, 0); /* create a socket */

	/* init servaddr */
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY); //#define INADDR_ANY   ((unsigned long int) 0x00000000)
	servaddr.sin_port = htons(15000);

	/* bind address and port to socket */
	if (bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1) {
		perror("UDP bind error");
		exit(1);
	}

	//pushstatus(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr));
	char* result = "";
	result = cmd_system("top -n 1|grep Cpu|awk '{print $2}'");
	//result = cmd_system("free |grep Mem | cut -d : -f 2|cut -d ' ' -f 8");
	printf("The result:%s\n", result);

	return 0;
}
